/*
 * Copyright (c) 2018. paascloud.net All Rights Reserved.
 * 项目名称：paascloud快速搭建企业级分布式微服务平台
 * 类名称：TokenInterceptor.java
 * 创建人：刘兆明
 * 联系方式：paascloud.net@gmail.com
 * 开源地址: https://github.com/paascloud
 * 博客地址: http://blog.paascloud.net
 * 项目官网: http://paascloud.net
 */

package com.weixing.mall.core.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.annotation.AgentLimit;
import com.weixing.mall.core.support.auth.AuthUtil;
import com.weixing.mall.core.support.auth.MemAuth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Date;

/**
 * 频率限制拦截器
 * <p>
 * The class Token interceptor.
 *
 * @author kfc
 */
@Slf4j
public class AgentInterceptor implements HandlerInterceptor {

    @Resource
    private ObjectMapper objectMapper;

    /**
     * Pre handle boolean.
     *
     * @param request  the request
     * @param response the response
     * @param handler  the handler
     * @return the boolean
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        AgentLimit noNeedAccessAnno = getAgentLimitAnno(handler);
        if (null != noNeedAccessAnno) {
            // 校验代理商是否有操作权限
            MemAuth memberExt = AuthUtil.getMemberExt();
            if (null == memberExt){
                Result error = ResultUtil.error("对不起，您无操作权限");
                sendResponse(response,error);
                return false;
            }else{
                Integer af = memberExt.getAf();
                if (0 == af){
                    Result error = ResultUtil.error("对不起，您无操作权限");
                    sendResponse(response,error);
                    return false;
                }else{
                    Date now = new Date();
                    if (now.compareTo(memberExt.getAbmt()) > 0){
                        Result error = ResultUtil.error("对不起，您的代理权益已到期");
                        sendResponse(response,error);
                        return false;
                    }
                }
            }
        }
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }


    private AgentLimit getAgentLimitAnno(Object handler) {
        AgentLimit access = null;
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            access = handlerMethod.getMethodAnnotation(AgentLimit.class);
        }
        return access;
    }


    private void sendResponse(HttpServletResponse response, Result result) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        try (OutputStream out = response.getOutputStream();
             PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, "utf-8"))) {
            // 返回json格式的提示
            pw.println(objectMapper.writeValueAsString(result));
        } catch (IOException ex) {
            log.warn("", ex);
        }
    }
}
